package com.mymarkdown.app.controller;

import com.mymarkdown.app.util.ReadFileImageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

/**
 * @author zenglun
 * @date 2021/12/6 5:22 下午
 * @description: TODO
 */
@Slf4j
@RequestMapping("/images")
@Controller
public class ImageController {

    @Value("${images.upload.path}")
    private String imagesSavePath;

    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return "上传失败，请选择文件";
        }

        String fileName = file.getOriginalFilename();
        String filePath = imagesSavePath;
        File dest = new File(filePath + fileName);
        try {
            file.transferTo(dest);
            log.info("上传成功");
            return "上传成功";
        } catch (IOException e) {
            log.error(e.toString(), e);
        }
        return "上传失败！";
    }


    /**
     * 显示任意文件夹下的文件
     * @param imagePath
     * @param response
     * @throws IOException
     */
    @GetMapping("/showImage")
    public void showImage(@RequestParam("path") String imagePath,  HttpServletResponse response) throws IOException {
        log.info("[ImageController]---[showImage],执行了，path:{}", imagePath);
        ReadFileImageUtil.showImage(imagePath, response);
    }
}
